package org.example.spring_blog.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.lang.Assert;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.ssl.SslBundleProperties;

import java.security.Key;
import java.util.Date;
import java.util.Map;


@Slf4j
public class jwtUtils {
    private static long expiration =  30 * 60 * 1000;  //30分钟过期
    private static String secretString = "XX7LWoRwue2WbMUlgopSdpofgAm3K0zIUenGsGD8D0l";
    private static Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    public static String getJwt(Map<String,Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+expiration))
                .signWith(key).compact();
    }

    /**
     * 校验解析令牌
     * @param jwt
     * @return
     */
    public static Claims parseJwt(String jwt) {
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();

        Claims claims = null;
        try {
            claims = build.parseClaimsJws(jwt).getBody();
        }catch (ExpiredJwtException e){
            log.error("token过期, 校验失败, token:"+ jwt);
        }catch (Exception e){
            log.error("token校验失败, token:"+ jwt);
        }

        return claims;
    }

    public static Integer getUserIdFromToken(String token){
        Claims claims = parseJwt(token);
        Assert.notNull(claims, "token不合法");
        Integer userId = (Integer) claims.get("id");
        return userId;
    }
}
